//
//  HistoryDetailViewController.m
//  MyWallet
//
//  Created by 美鑫科技 on 16/8/5.
//  Copyright © 2016年 MorpLCP. All rights reserved.
//

#import "HistoryDetailViewController.h"
#import "DetailViewController.h"

@interface HistoryDetailViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

@end

@implementation HistoryDetailViewController

static NSString *cellIdent = @"historydetaillistcell";

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initSubViews];
}

- (void)initSubViews
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(
                                                                   0,
                                                                   0,
                                                                   ScreenWidth,
                                                                   ScreenHeight
                                                                   ) style:(UITableViewStyleGrouped)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIdent];
    [self.view addSubview:_tableView];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataDict.allKeys.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSMutableArray *keyArray = self.dataDict.allKeys.mutableCopy;
    /*排序*/
    [keyArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2)
     {
         NSDateFormatter *formater = [[NSDateFormatter alloc] init];
         [formater setDateFormat:@"yyyy-MM-dd"];
         NSDate *date1 = [formater dateFromString:obj1];
         NSDate *date2 = [formater dateFromString:obj2];
         if ([[date1 earlierDate:date2] isEqual:date1]) return NSOrderedDescending;
         else return NSOrderedAscending;
     }];
    NSArray *billArray = self.dataDict[keyArray[section]];
    return billArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdent forIndexPath:indexPath];
    NSMutableArray *keyArray = self.dataDict.allKeys.mutableCopy;
    /*排序*/
    [keyArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2)
     {
         NSDateFormatter *formater = [[NSDateFormatter alloc] init];
         [formater setDateFormat:@"yyyy-MM-dd"];
         NSDate *date1 = [formater dateFromString:obj1];
         NSDate *date2 = [formater dateFromString:obj2];
         if ([[date1 earlierDate:date2] isEqual:date1]) return NSOrderedDescending;
         else return NSOrderedAscending;
     }];
    NSArray *billArray = self.dataDict[keyArray[indexPath.section]];
    Bill *bill = billArray[indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    NSInteger type = bill.bType;
    if (type == 0)
    {
        cell.imageView.image = [UIImage imageNamed:@"out"];
        NSString *txt = [NSString stringWithFormat:@"【%@】花费：￥%.2f", bill.bUse, bill.bMoney];
        cell.textLabel.text = txt;
    }
    else
    {
        cell.imageView.image = [UIImage imageNamed:@"in"];
        NSString *txt = [NSString stringWithFormat:@"【%@】收入：￥%.2f", bill.bUse, bill.bMoney];
        cell.textLabel.text = txt;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

// 分区头部显示收入、支出总结
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSMutableArray *keyArray = self.dataDict.allKeys.mutableCopy;
    /*排序*/
    [keyArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2)
     {
         NSDateFormatter *formater = [[NSDateFormatter alloc] init];
         [formater setDateFormat:@"yyyy-MM-dd"];
         NSDate *date1 = [formater dateFromString:obj1];
         NSDate *date2 = [formater dateFromString:obj2];
         if ([[date1 earlierDate:date2] isEqual:date1]) return NSOrderedDescending;
         else return NSOrderedAscending;
     }];
    NSString *dateStr = @"";
    if ([keyArray[section] isEqualToString:[FinalTools currentDateWithFormat:@"yyyy-MM-dd"]])
    {
        dateStr = @"今天";
    }
    else
    {
        dateStr = keyArray[section];
    }
    NSString *tempStr = [[BillManager manager] getConclusionWithDate:keyArray[section]];
    return [NSString stringWithFormat:@"%@ (收入：￥%@, 支出：￥%@)", dateStr,  [tempStr componentsSeparatedByString:@","].firstObject, [tempStr componentsSeparatedByString:@","].lastObject];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 35;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(
                                                                  0,
                                                                  0,
                                                                  ScreenWidth,
                                                                  30
                                                                  )];
    UILabel *lblMoney = [[UILabel alloc] initWithFrame:CGRectMake(
                                                                  0,
                                                                  0,
                                                                  ScreenWidth,
                                                                  30
                                                                  )];
    // 设置底部视图阴影
    UIImageView *shadowView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"jianbian"]];
    shadowView.frame = CGRectMake(
                                  0,
                                  0,
                                  ScreenWidth,
                                  3
                                  );
    [footerView addSubview:shadowView];
    footerView.backgroundColor = COLOR_RGB(0xdddddd);
    lblMoney.textAlignment = NSTextAlignmentCenter;
    lblMoney.font = [UIFont systemFontOfSize:13];
    lblMoney.textColor = [UIColor darkGrayColor];
    NSMutableArray *keyArray = self.dataDict.allKeys.mutableCopy;
    /*排序*/
    [keyArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2)
     {
         NSDateFormatter *formater = [[NSDateFormatter alloc] init];
         [formater setDateFormat:@"yyyy-MM-dd"];
         NSDate *date1 = [formater dateFromString:obj1];
         NSDate *date2 = [formater dateFromString:obj2];
         if ([[date1 earlierDate:date2] isEqual:date1]) return NSOrderedDescending;
         else return NSOrderedAscending;
     }];
    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"Budget_day"])
    {
        NSArray *billArray = self.dataDict[keyArray[section]];
        Bill *bill = [billArray lastObject];
        double money = bill.bBalance;
        NSString *moneyStr = @"";
        if ([keyArray[section] isEqualToString:[FinalTools currentDateWithFormat:@"yyyy-MM-dd"]])
        {
            moneyStr = [NSString stringWithFormat:@"今日余额:￥%.2f", money];
        }
        else
        {
            moneyStr = [NSString stringWithFormat:@"当日余额:￥%.2f", money];
        }
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:moneyStr];
        if (money >= 0)
        {
            [attrStr addAttribute:NSForegroundColorAttributeName
                            value:RgbColor(20, 143, 70)
                            range:[moneyStr rangeOfString:[NSString stringWithFormat:@"￥%.2f", money]]];
            [attrStr addAttribute:NSFontAttributeName
                            value:[UIFont systemFontOfSize:20]
                            range:[moneyStr rangeOfString:[NSString stringWithFormat:@"￥%.2f", money]]];
            lblMoney.attributedText = attrStr;
        }
        else
        {
            [attrStr addAttribute:NSForegroundColorAttributeName
                            value:[UIColor redColor]
                            range:[moneyStr rangeOfString:[NSString stringWithFormat:@"￥%.2f", money]]];
            [attrStr addAttribute:NSFontAttributeName
                            value:[UIFont systemFontOfSize:20]
                            range:[moneyStr rangeOfString:[NSString stringWithFormat:@"￥%.2f", money]]];
            lblMoney.attributedText = attrStr;
        }
    }
    else
    {
        double outMoney_day = [[[[BillManager manager] getConclusionWithDate:keyArray[section]] componentsSeparatedByString:@","].lastObject doubleValue];
        double budgetMoney_day = [[[NSUserDefaults standardUserDefaults] objectForKey:@"Budget_day"] doubleValue];
        double remaining_day = budgetMoney_day - outMoney_day;
        double outMoney_month = [[[[BillManager manager] getConclusion_Month_NoBlock] componentsSeparatedByString:@","].lastObject doubleValue];
        double budgetMoney_month = [[[NSUserDefaults standardUserDefaults] objectForKey:@"Budget_month"] doubleValue];
        double remaining_month = budgetMoney_month - outMoney_month;
        NSString *moneyStr = @"";
        if ([keyArray[section] isEqualToString:[FinalTools currentDateWithFormat:@"yyyy-MM-dd"]])
        {
            moneyStr =  [NSString stringWithFormat:@"今日预算:￥%.2f 本月预算:￥%.2f", remaining_day, remaining_month];
        }
        else
        {
            moneyStr =  [NSString stringWithFormat:@"当日预算:￥%.2f 本月预算:￥%.2f", remaining_day, remaining_month];
        }
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:moneyStr];
        if (remaining_month > 0 && remaining_day > 0)
        {
            NSString *day_rangeStr = [NSString stringWithFormat:@"￥%.2f", remaining_day];
            NSString *month_rangeStr = [NSString stringWithFormat:@"￥%.2f", remaining_month];
            if ([day_rangeStr isEqualToString:month_rangeStr])
            {
                NSRange tempRange = [moneyStr rangeOfString:day_rangeStr];
                NSRange range = NSMakeRange(
                                            tempRange.location + tempRange.length + 6,
                                            tempRange.length
                                            );
                [attrStr addAttribute:NSForegroundColorAttributeName
                                value:RgbColor(20, 143, 70)
                                range:[moneyStr rangeOfString:day_rangeStr]];
                [attrStr addAttribute:NSFontAttributeName
                                value:[UIFont systemFontOfSize:17]
                                range:[moneyStr rangeOfString:day_rangeStr]];
                [attrStr addAttribute:NSForegroundColorAttributeName
                                value:RgbColor(20, 143, 70)
                                range:range];
                [attrStr addAttribute:NSFontAttributeName
                                value:[UIFont systemFontOfSize:17]
                                range:range];
            }
            else
            {
                [attrStr addAttribute:NSForegroundColorAttributeName
                                value:RgbColor(20, 143, 70)
                                range:[moneyStr rangeOfString:[NSString stringWithFormat:@"￥%.2f", remaining_day]]];
                [attrStr addAttribute:NSFontAttributeName
                                value:[UIFont systemFontOfSize:17]
                                range:[moneyStr rangeOfString:[NSString stringWithFormat:@"￥%.2f", remaining_day]]];
                [attrStr addAttribute:NSForegroundColorAttributeName
                                value:RgbColor(20, 143, 70)
                                range:[moneyStr rangeOfString:[NSString stringWithFormat:@"￥%.2f", remaining_month]]];
                [attrStr addAttribute:NSFontAttributeName
                                value:[UIFont systemFontOfSize:17]
                                range:[moneyStr rangeOfString:[NSString stringWithFormat:@"￥%.2f", remaining_month]]];
            }
            lblMoney.attributedText = attrStr;
        }
        else if (remaining_day > 0 && remaining_month <= 0)
        {
            [attrStr addAttribute:NSForegroundColorAttributeName
                            value:RgbColor(20, 143, 70)
                            range:[moneyStr rangeOfString:[NSString stringWithFormat:@"￥%.2f", remaining_day]]];
            [attrStr addAttribute:NSFontAttributeName
                            value:[UIFont systemFontOfSize:17]
                            range:[moneyStr rangeOfString:[NSString stringWithFormat:@"￥%.2f", remaining_day]]];
            [attrStr addAttribute:NSForegroundColorAttributeName
                            value:[UIColor redColor]
                            range:[moneyStr rangeOfString:[NSString stringWithFormat:@"￥%.2f", remaining_month]]];
            [attrStr addAttribute:NSFontAttributeName
                            value:[UIFont systemFontOfSize:17]
                            range:[moneyStr rangeOfString:[NSString stringWithFormat:@"￥%.2f", remaining_month]]];
            lblMoney.attributedText = attrStr;
        }
        else if (remaining_day <= 0 && remaining_month > 0)
        {
            [attrStr addAttribute:NSForegroundColorAttributeName
                            value:[UIColor redColor]
                            range:[moneyStr rangeOfString:[NSString stringWithFormat:@"￥%.2f", remaining_day]]];
            [attrStr addAttribute:NSFontAttributeName
                            value:[UIFont systemFontOfSize:17]
                            range:[moneyStr rangeOfString:[NSString stringWithFormat:@"￥%.2f", remaining_day]]];
            [attrStr addAttribute:NSForegroundColorAttributeName
                            value:RgbColor(20, 143, 70)
                            range:[moneyStr rangeOfString:[NSString stringWithFormat:@"￥%.2f", remaining_month]]];
            [attrStr addAttribute:NSFontAttributeName
                            value:[UIFont systemFontOfSize:17]
                            range:[moneyStr rangeOfString:[NSString stringWithFormat:@"￥%.2f", remaining_month]]];
            lblMoney.attributedText = attrStr;
        }
        else
        {
            NSString *day_rangeStr = [NSString stringWithFormat:@"￥%.2f", remaining_day];
            NSString *month_rangeStr = [NSString stringWithFormat:@"￥%.2f", remaining_month];
            if ([day_rangeStr isEqualToString:month_rangeStr])
            {
                NSRange tempRange = [moneyStr rangeOfString:day_rangeStr];
                NSRange range = NSMakeRange(
                                            tempRange.location + tempRange.length + 6,
                                            tempRange.length
                                            );
                [attrStr addAttribute:NSForegroundColorAttributeName
                                value:[UIColor redColor]
                                range:[moneyStr rangeOfString:day_rangeStr]];
                [attrStr addAttribute:NSFontAttributeName
                                value:[UIFont systemFontOfSize:17]
                                range:[moneyStr rangeOfString:day_rangeStr]];
                [attrStr addAttribute:NSForegroundColorAttributeName
                                value:[UIColor redColor]
                                range:range];
                [attrStr addAttribute:NSFontAttributeName
                                value:[UIFont systemFontOfSize:17]
                                range:range];
            }
            else
            {
                [attrStr addAttribute:NSForegroundColorAttributeName
                                value:[UIColor redColor]
                                range:[moneyStr rangeOfString:day_rangeStr]];
                [attrStr addAttribute:NSFontAttributeName
                                value:[UIFont systemFontOfSize:17]
                                range:[moneyStr rangeOfString:day_rangeStr]];
                [attrStr addAttribute:NSForegroundColorAttributeName
                                value:[UIColor redColor]
                                range:[moneyStr rangeOfString:month_rangeStr]];
                [attrStr addAttribute:NSFontAttributeName
                                value:[UIFont systemFontOfSize:17]
                                range:[moneyStr rangeOfString:month_rangeStr]];
            }
            lblMoney.attributedText = attrStr;
        }
    }
    [footerView addSubview:lblMoney];
    return footerView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *keyArray = self.dataDict.allKeys.mutableCopy;
    /*排序*/
    [keyArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2)
     {
         NSDateFormatter *formater = [[NSDateFormatter alloc] init];
         [formater setDateFormat:@"yyyy-MM-dd"];
         NSDate *date1 = [formater dateFromString:obj1];
         NSDate *date2 = [formater dateFromString:obj2];
         if ([[date1 earlierDate:date2] isEqual:date1]) return NSOrderedDescending;
         else return NSOrderedAscending;
     }];
    NSArray *billArray = self.dataDict[keyArray[indexPath.section]];
    Bill *bill = billArray[indexPath.row];
    DetailViewController *detailVC = [DetailViewController new];
    detailVC.bill = bill;
    detailVC.canDelete = NO;
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
